<template>
  <el-dialog
    title="选择优惠券"
    v-model="visible"
    width="1100px"
    @close="onClose"
    :close-on-click-modal="false"
    :lock-scroll="false"
  >
    <div class="main">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input
            style="width: 200px"
            maxlength="16"
            v-model.trim="queryParams.couponName"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="名称备注" prop="couponRemark">
          <el-input
            style="width: 200px"
            maxlength="30"
            v-model.trim="queryParams.couponRemark"
            placeholder="请输入名称备注"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="queryParams.type" fit-input-width clearable placeholder="请选择">
            <el-option
              v-for="item in ACTIVITY_TYPE"
              :key="item.type"
              :label="item.title"
              :value="item.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">刷新</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="selectedTableRef"
        v-loading="loading"
        size="default"
        index
        row-key="id"
        :data="dataList"
        highlight-current-row
        @current-change="currentChange"
      >
        <el-table-column
          label="优惠券名称"
          min-width="150px"
          align="center"
          show-overflow-tooltip
          prop="couponName"
        />
        <el-table-column
          label="名称备注"
          min-width="100px"
          align="center"
          show-overflow-tooltip
          prop="couponRemark"
        />
        <el-table-column label="类型" width="100px" align="center" prop="type">
          <template #default="{ row }">
            <div>
              {{ getType(row.type) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="优惠内容"
          width="150px"
          show-overflow-tooltip
          align="center"
          prop="details"
        />
        <el-table-column label="剩余库存" align="center" prop="surplusCount" />
        <el-table-column label="每人限领次数" align="center" prop="receiveCount" />
        <el-table-column label="赠券数" min-widt="200px" align="center">
          <template #default="{ row }">
            <div :class="row.empty ? 'empty' : ''">
              <el-input-number
                :controls="false"
                style="width: 90px"
                v-model="row.couponCount"
                :min="1"
                :max="getMax(row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <template #footer>
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCouponListApi } from '@/api/marketing/giftPack'
import { listDataApi } from '@/api/system/dict/data'

const emit = defineEmits(['select'])
const queryRef = ref(null)

const total = ref(0)
const dataList = ref([])
const visible = ref(false)
const submit = ref(false)
const isFirst = ref(false)
const selectedIndex = ref(-1)

const queryParams = reactive({
  couponName: '',
  type: '',
  couponRemark: '',
  cityName: '全国',
  pageNum: 1,
  pageSize: 10
})
const oldPageNum = ref(1)
const loading = ref(true)

// =========获取优惠券类型列表
const ACTIVITY_TYPE = ref([])
const getListData = () => {
  listDataApi({ dictType: 'market_activity_type' }).then((res) => {
    ACTIVITY_TYPE.value = res?.rows.map((i) => {
      return {
        title: i.dictLabel,
        dec: i.remark,
        type: i.dictValue - 0
      }
    })
  })
}
function getType(type) {
  return ACTIVITY_TYPE.value.find((i) => {
    return i.type == type
  })?.title
}

function getMax(row) {
  if (row.receiveCount > 0 && row.receiveCount <= row.surplusCount) {
    return row.receiveCount
  } else if (row.surplusCount > 0 && row.receiveCount >= row.surplusCount) {
    return row.surplusCount
  } else {
    return 1
  }
}
/**单选 优惠券列表 */
function currentChange(row) {
  selectedTableItem.value = row
  console.log('selectedTableItem', selectedTableItem.value)
  // dataList.value.forEach((i) => {
  //   if (i.couponCount) {
  //     i.couponCount = null
  //   }
  // })
}
/**======================= 查询优惠券列表 */
function getList() {
  // console.log('oldSelectedTableItem', oldSelectedTableItem.value)

  oldPageNum.value = queryParams.pageNum
  loading.value = true
  getCouponListApi(queryParams)
    .then((res) => {
      loading.value = false
      dataList.value = res?.data?.rows || []
      // if (oldSelectedTableItem.value) {
      //   selectedTableRef.value?.setCurrentRow(oldSelectedTableItem.value)
      //   dataList.value.forEach((i) => {
      //     if (i.id === oldSelectedTableItem.value.id) {
      //       i.couponCount = oldSelectedTableItem.value.couponCount
      //     }
      //   })
      // }
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
      dataList.value = []
      total.value = 0
    })
}
// 刷新
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}
// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function onClose() {
  submit.value = false
  queryRef.value.resetFields()
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  oldPageNum.value = 1
  // oldSelectedTableItem.value = selectedTableItem.value
  // selectedTableItem.value = oldSelectedTableItem.value
  visible.value = false
}

//========================= 单选==================
const selectedTableRef = ref(null)
const selectedTableItem = ref()
// const oldSelectedTableItem = ref()
// 选择
// function handleSelectionChange(val) {
//   console.log(val)
//   // multipleSelection.value = val
// }

// 校验是否可以提交或者切换页码
function handleCheck() {
  if (!selectedTableItem.value?.couponCount) {
    dataList.value.forEach((i) => {
      if (i.id === selectedTableItem.value.id) {
        i.empty = true
      } else {
        i.empty = false
      }
    })
  }
  return selectedTableItem.value?.couponCount
}
// 选中或清除选中
// function toggleSelection(rows, ignoreSelectable) {
//   if (rows) {
//     rows.forEach((row) => {
//       multipleTableRef.value.toggleRowSelection(row, undefined, ignoreSelectable)
//     })
//   } else {
//     multipleTableRef.value.clearSelection()
//   }
// }

/**提交 */
function handleAction(confirm) {
  if (confirm) {
    if (!selectedTableItem.value) {
      ElMessage({
        type: 'error',
        message: '请选择优惠券'
      })
      return
    }
    if (!handleCheck()) {
      ElMessage({
        type: 'error',
        message: '请校验数据'
      })
      return
    }
    submit.value = true
    emit('select', selectedTableItem.value, isFirst.value, selectedIndex.value)
    onClose()
  } else {
    onClose()
  }
}

function init(type, item, index) {
  console.log(type, item, index)
  visible.value = true
  isFirst.value = type
  selectedIndex.value = index
  // oldSelectedTableItem.value = { ...item }
  // selectedTableItem.value = { ...item }
  getList()
  getListData()
  // nextTick(() => {
  //   // 先清除再选中
  //   toggleSelection()
  //   toggleSelection(list, true)
  // })
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
:deep(.pagination-container .el-pagination) {
  right: 20px;
}
.main {
  position: relative;
  transform: translate3d(0, -30px, 0);
}
.type {
  margin-bottom: 20px;
}
// :deep(.el-table th.el-table__cell:nth-child(1) .cell) {
//   visibility: hidden;
// }
:deep(.empty .el-input__wrapper) {
  border: 1px solid red;
}
</style>
